<template>
  <div class="infinite-container">
    <div class="login" v-if="showLogin">
      <mu-flexbox class="bgwhite">
        <mu-flexbox-item grow="1"></mu-flexbox-item>
        <mu-flexbox-item grow="18">
          <mu-text-field hintText="请输入手机号" v-model="phoneNumber" type="text" fullWidth></mu-text-field>
        </mu-flexbox-item>
        <mu-flexbox-item grow="1"></mu-flexbox-item>
      </mu-flexbox>
      <mu-divider/>

      <mu-flexbox class="bgwhite">
        <mu-flexbox-item grow="1"></mu-flexbox-item>
        <mu-flexbox-item grow="10">
          <mu-text-field hintText="验证码" v-model="vcode" type="text" fullWidth></mu-text-field>
        </mu-flexbox-item>
        <mu-flexbox-item grow="8" class="text-right">
         <mu-raised-button :label="vcodeLabel" @click="getVcode"  class="small" fullWidth primary :disabled="vcodeDisabled"></mu-raised-button>
        </mu-flexbox-item>
        <mu-flexbox-item grow="1"></mu-flexbox-item>
      </mu-flexbox>
      <mu-divider/>

      <mu-flexbox :gutter="0" style="margin-top:4em;">
        <mu-flexbox-item grow="2"></mu-flexbox-item>
        <mu-flexbox-item grow="16">
         <mu-raised-button class="submit-btn" label="绑定并登陆" @click="bind" fullWidth primary></mu-raised-button>
        </mu-flexbox-item>
        <mu-flexbox-item grow="2"></mu-flexbox-item>
      </mu-flexbox>
      <p class="login-text">{{tipText}}</p>
    </div>
    <p class="login center" v-else>
      正在登陆中，请稍后......
    </p>

        <mu-dialog :open="dialogOpen" >
            <div class="t2">功能测试中</div>
            <mu-text-field hintText="请输入测试密码" v-model="testPassword" type="text" fullWidth></mu-text-field>
            <mu-flat-button slot="actions" @click="safeConfirm" primary label="确定"/>
          </mu-dialog>
    </div>

</template>
<script>
import {commonAjax, RESTFUL_API} from '@/api/api'
import {testPhone, testVcode} from '@/common/js/util.js'
// import md5 from 'md5'
const VCODE_LABEL_DEFALT = '获取验证码'
export default {
  data () {
    return {
      phoneNumber: '',
      vcode: '',
      vcodeLabel: VCODE_LABEL_DEFALT,
      vcodeDisabled: false,
      showLogin: false,
      dialogOpen: false,
      testPassword: '',
      tipText: ''
    }
  },
  methods: {
    getSelf () {
      if (!sessionStorage[this.$APP_PLATFORM_NAME]) {
        this.showLogin = true
        return
      }
      // 此处有坑：入参openid为小写， aliUid没问题
      let params = {}
      // if (this.$APP_PLATFORM === 1) {
      //   params.openid = sessionStorage[this.$APP_PLATFORM_NAME]
      // } else {
      params[this.$APP_PLATFORM_NAME] = sessionStorage[this.$APP_PLATFORM_NAME]
      // }
      commonAjax(RESTFUL_API.getSelf, params).then(res => {
          if (res.data.code == 200) {
          // if this is a new user
          // res.data.data should be null
          let data = res.data.data
          if (data === null) {
            // todo: bind new user
            this.showLogin = true
          } else {
            sessionStorage.accessToken = data.token
            sessionStorage.person = sessionStorage.familyPerson = JSON.stringify(data)
            const redirect = this.$route.query.redirect
            if (data.idcard) {
              let redirectUrl = redirect || '/setting'
              this.$router.replace(redirectUrl)
            } else {
              console.log(`跳转URL:${redirect}`)
              let s = `/setting?${this.$APP_PLATFORM_NAME}`
              if (redirect && redirect.indexOf(s) > -1) {
                this.$router.replace('/setting')
                return
              }
              this.$store.commit('UPDATE_TOAST', {
                message: '请先完善个人信息',
                fn: () => this.$router.push('/setting/improve-user-info')
              })
            }
          }
        } else {
          this.$store.commit('UPDATE_TOAST', {message: res.data.msg})
        }
      })
    },
    bind () {
      if (!this.phoneNumber || !this.vcode) {
        return false
      }
      if (!testPhone(this.phoneNumber) || !testVcode(this.vcode)) {
        this.$store.commit('UPDATE_TOAST', {message: '手机号或密码有误'})
        return false
      }
      let params = {
        mobile: this.phoneNumber,
        code: this.vcode,
        [this.$APP_PLATFORM_NAME]: sessionStorage[this.$APP_PLATFORM_NAME]
      }
      commonAjax(RESTFUL_API.bind, params).then(res => {
        if (res.data.code == 200) {
          // todo: bind success or already bind
          this.$store.commit('UPDATE_TOAST', {
            message: '绑定成功',
            fn: () => this.getSelf(),
            timeout: 400
          })
        } else {
          this.$store.commit('UPDATE_TOAST', {
            message: res.data.msg,
            timeout: 3000
          })
        }
      })
    },
    getVcode () {
      if (testPhone(this.phoneNumber)) {
        this.vcodeDisabled = true
        commonAjax(`${RESTFUL_API.sendSmsCode}`, {mobile: this.phoneNumber}).then(res => {
          if (res.data.code == 200) {
            this.$store.commit('UPDATE_TOAST', {message: '验证码发送成功'})
            this.timeout()
          } else {
            this.vcodeDisabled = false
            this.$store.commit('UPDATE_TOAST', {message: res.data.msg})
          }
        }).catch(e => {
          console.warn(e)
          this.$store.commit('UPDATE_TOAST', {message: '服务错误'})
          this.vcodeDisabled = false
        })
      } else {
        this.$store.commit('UPDATE_TOAST', {message: '请输入有效的手机号'})
      }
    },
    timeout () {
      let start = 60
      let countDown = () => {
        this.vcodeTimer = setTimeout(() => {
          this.vcodeLabel = (start--) + ''
          countDown()
          if (start <= 0) {
            this.vcodeDisabled = false
            this.vcodeLabel = VCODE_LABEL_DEFALT
            clearTimeout(this.vcodeTimer)
          }
        }, 1000)
      }
      countDown()
    },
    safeConfirm () {
      // todo
      if (this.testPassword === 'bsoftbsoft') {
        localStorage.testPassword = 'bsoftbsoft'
        this.getSelf()
        this.dialogOpen = false
      }
    }
  },
  mounted () {
    // if (localStorage.testPassword !== 'bsoftbsoft') {
    //   this.dialogOpen = true
    // } else {
    this.getSelf()
    // }
    this.tipText = this.$APP_PLATFORM === 1 ? '绑定即同意微信授权登陆' : '绑定即同意支付宝授权登陆'
  },
  beforeDestroy () {
  }
}
</script>

<style lang="less">
@import '../common/css/vars.less';
.login-text {
  color: #999;
  text-align:center;
}
</style>
